﻿using System;
using System.Collections.Generic;
using Basic.Model.Entity;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;

namespace Basic.Model.EntityManager
{
    public class RoleManager
    {
        public static void Add(ISession session, Role an)
        {
            session.Save(an);
        }

        public static void Delete(ISession session, Role an)
        {
            session.Delete(an);
        }

        public static void Update(ISession session, Role an)
        {
            session.Update(an);
        }

        public static Role Get(ISession session, int itemId)
        {
            return session.Get<Role>(itemId);
        }

        public static Role GetByCondition(ISession session, int roleId, string roleName, bool isRoleGroup)
        {
            ICriteria c = session.CreateCriteria(typeof(Role));
            if (roleId >= 0)
                c.Add(Expression.Eq("roleId", roleId));
            if (!String.IsNullOrEmpty(roleName))
                c.Add(Expression.Eq("roleName", roleName));
            if (isRoleGroup)
            {
                c.SetFetchMode("roleGroup", FetchMode.Eager);
            }
            return c.UniqueResult<Role>();
        }

        public static IList<Role> GetAll(ISession session)
        {
            ICriteria c = session.CreateCriteria(typeof(Role));
            return c.List<Role>();
        }

        public static IList<Role> GetAllByCondition(ISession session, bool isRoleGroup, int rowIndex, int rowCount)
        {
            ICriteria c = session.CreateCriteria(typeof(Role));
            if (rowIndex >= 0)
                c.SetFirstResult(rowIndex);
            if (rowCount >= 0)
                c.SetMaxResults(rowCount);
            if (isRoleGroup)
            {
                c.SetFetchMode("roleGroup", FetchMode.Eager);
            }
            return c.List<Role>();
        }
        public static int GetAllByConditionCount(ISession session)
        {
            ICriteria c = session.CreateCriteria(typeof(Role));
            return (int)c.SetProjection(Projections.Count("roleId")).UniqueResult();
        }
    }
}
